<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>IntersectionObserver</title>
  <style>
    html,
    body {
      height: 100%;
      margin: 0;
      overflow-anchor: none;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="blank">更多...</div>
  </div>
  <script>
    const container = document.querySelector('.container');
    const blank = document.querySelector('.blank');

    const renderList1 = function () {
      const total = 100000;
      // 懒加载的思路 -- 分段渲染
      // 1. 一次渲染一屏的量
      const once = 100;
      // 2. 全部渲染完需要多少次，循环的时候要用
      const loopCount = Math.ceil(total / once);
      // 3. 已经渲染了多少次
      let countHasRender = 0;

      function add() {
        // 创建虚拟节点，（使用 createDocumentFragment 不会触发渲染）
        const fragment = document.createDocumentFragment();
        // 循环 20 次
        for (let i = 0; i < once; i++) {
          const div = document.createElement('div');
          div.innerText = Math.floor(Math.random() * total);
          div.className = 'item';
          fragment.appendChild(div);
        }
        // 最后把虚拟节点 append 到 ul 上
        container.appendChild(fragment);
        // 4. 已渲染的次数 + 1
        countHasRender += 1;
        loop();
      }

      // 最重要的部分来了
      function loop() {
        // 5. 如果还没渲染完，那么就使用 requestAnimationFrame 来继续渲染
        if (countHasRender < loopCount) {
          // requestAnimationFrame 叫做逐帧渲染
          // 类似于 setTimeout(add, 16);
          // 帧：一秒钟播放多少张图片，一秒钟播放的图片越多，动画就约流畅
          // 1000/60 = 0.16s
          window.requestAnimationFrame(add);
        }
      }

      loop();
    };
    // renderList1();
    function renderList2() {
      const list = new Array(100000).fill(99);
      const total = list.length,
        page = 0,
        limit = 100,
        totalPage = Math.ceil(total / limit);
      const render = (page) => {
        if (page >= totalPage) return;
        window.requestAnimationFrame(() => {
          const fragment = document.createDocumentFragment();

          for (let i = page * limit; i < (page + 1) * limit; i++) {
            const item = list[i];
            const div = document.createElement('div');
            div.className = 'item';
            div.textContent = Math.floor(Math.random() * total);
            // div.textContent = item;
            fragment.appendChild(div);
          }

          container.appendChild(fragment);
        });

        render(page++);
      };

      render(page);
    }
    // renderList2();



    // [].slice(pagenum * pagesize, (pagenum + 1) * pagesize) // pagesize默认为0时的分页条件
    // [].slice((pagenum - 1) * pagesize, pagenum * pagesize) // pagesize默认为1时的分页条件

    function renderList3() {
      const list = new Array(100000).fill(0);
      let total = list.length,
        page = 1,
        limit = 50,
        totalPage = Math.ceil(total / limit);

      const render = (page) => {
        requestAnimationFrame(() => {

          if (page >= totalPage) {
            observer?.unobserve(blank);
            return;
          }
          const fragment = document.createDocumentFragment();
          for (let i = (page - 1) * limit; i < page * limit; i++) {
            const item = list[i];
            const div = document.createElement('div');
            div.textContent = `${page}-${i + 1}`
            fragment.appendChild(div);
          }
          container.insertBefore(fragment, blank);
        });
      };

      const observer = new IntersectionObserver(
        (entries) => {
          console.log('entries', entries[0].isIntersecting);
          if (!entries[0].isIntersecting) return;
          render(page++);
        },
        { rootMargin: '0px 0px 100px 0px', }
      );

      observer.observe(blank);
      render(page);
    }
    renderList3();
  </script>
</body>

</html>